import datetime
import json
import os
from json import JSONEncoder
from pathlib import Path


class DateTimeEncoder(JSONEncoder):
        #Override the default method
        def default(self, obj):
            if isinstance(obj, (datetime.date, datetime.datetime)):
                return obj.isoformat()


class ConfigJson():
    def  __init__(self, cfgfile) -> None:
        self.cfgfile = os.path.join(os.getcwd(),cfgfile)
        # print(self.cfgfile)


        if Path(self.cfgfile).exists():
            # print('Config file exists')
            self.readFile()
        else:
            # print('Config file does not exist')
            self.cfg = {}
    
    def readFile(self):
        """从文件读取配置参数"""
        with open(self.cfgfile, 'r', encoding='utf-8') as f:
            self.cfg = json.loads(f.read())

    def rv(self,lt):
        for i in range(len(lt)):
            if i > 0 :
                temp = temp[lt[i]]
            else:
                temp = self.cfg[lt[0]]
        return temp


    def readValue(self, section, item):
        """读取item值"""
        # print(f"section: {section}, item: {item}")
        try:

            return self.cfg[section][item]
        except KeyError:
            return 'novlaue'

    def setValue(self, section, item, value):
        """写入item值"""
        value_original = self.readValue(section, item)
        if value_original != value:
            self.cfg[section][item] = value
            self.updateFile()

    def updateFile(self):
        """修改参数后更新文件"""
        with open(self.cfgfile, 'w', encoding='utf-8') as f:
            json.dump(self.cfg, f,
                      sort_keys=True, 
                      indent=4, 
                      ensure_ascii=False,
                      cls=DateTimeEncoder)
#
# """
#   File "E:\llm\server\index_admin.py", line 20, in <module>
#     from config import cfg
#   File "E:\llm\server\config.py", line 54, in <module>
#     print(cfg.readValue("out_search","datadir"))
#   File "E:\llm\server\config.py", line 32, in readValue
#     return self.cfg[section][item]
# KeyError: 'out_search'
# """
cfg = ConfigJson('config.json')
# print(cfg.readValue("out_search","embedding_model_dict"))
# print(cfg.rv(["out_search","embedding_model_dict","BGEM3FlagModel"]))